package com.hs.auth.viewmodel


import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hs.ZaFingerprintHelper
import com.hs.common.dto.SysUserDto
import com.hs.common.repository.IUserRepository
import com.hs.framework.toast.TipsToast
import com.hs.framework.utils.HashUtils
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(private  var userService : IUserRepository ,
                                          var fingerprintHelper: ZaFingerprintHelper) : ViewModel() {

    val liveData = MutableLiveData<SysUserDto>()

    val errorData = MutableLiveData<String>()

    /**
     *  通过账号查询密码
     */
    fun loginByAccount(account: String,password:String){
       viewModelScope.launch(Dispatchers.IO) {
             userService.selectByAccount(account).let {
                   withContext(Dispatchers.Main){
                       if (it != null){
                           if (HashUtils.sha1(password) != it.password){
                               TipsToast.showTips("您输入的密码错误")
                           }else{
                               liveData.value = it
                           }
                       }else{
                           TipsToast.showTips("账号不存在")
                       }
                   }
               }
           }
    }

    /**
     *  通过指纹ID查找用户信息
     */
    fun findByFingerId(){
        viewModelScope.launch(Dispatchers.IO) {
            fingerprintHelper.searchFinger().collect{
                if (it.status == 0){
                    userService.selectByFingerId(it.templateId!!)?.let {
                        withContext(Dispatchers.Main){
                            liveData.value = it
                        }
                    }?:run{
                        withContext(Dispatchers.Main){
                            errorData.value = "搜索不到与指纹匹配的人员信息"
                        }
                    }
                }else{
                    println("${it.msg}")
                    withContext(Dispatchers.Main){
                        errorData.value = it.msg
                    }
                }
            }
        }
    }

    /**
     * 打开指纹串口
     */
    fun openUsbDev(){
        viewModelScope.launch(Dispatchers.IO) {
            fingerprintHelper.stop()
            fingerprintHelper.openDev()
        }
    }

    /**
     * 停止指纹串口
     */
    fun stopUsbDev(){
        viewModelScope.launch(Dispatchers.IO) {
            fingerprintHelper.stop()
            fingerprintHelper.closeDev()
        }
    }

    /**
     * 停止
     */
    fun stopUsb(){
        viewModelScope.launch(Dispatchers.IO) {
            fingerprintHelper.stop()
        }
    }


 }


